<?php

class PotentialsController extends AppController
{

    var $name = 'Potentials';

    function beforeFilter()
    {
        parent::beforeFilter();
    }

    function index()
    {
        if( empty($this->passedArgs['by']) || empty($this->passedArgs['show']) )
        {
            $this->redirect(array('controller' => 'potentials', 'action' => 'index', 'by' => 'leads', 'show' => 'all'));
        }

        if( $this->RequestHandler->isAjax() )
        {
            //pr($this->params);
            $this->autoRender = false;

            // get how many rows we want to have into the grid - rowNum parameter in the grid
            $limit = $this->params['url']['rows'];

            // get index row - i.e. user click to sort. At first time sortname parameter -
            // after that the index from colModel
            $sidx = $this->params['url']['sidx'];

            // sorting order - at first time sortorder
            $sord = $this->params['url']['sord'];

            $page = $this->params['url']['page'];

            // if we not pass at first time index use the first column for the index or what you want
            if( !$sidx ) $sidx = 1;

            // calculate the number of rows for the query. We need this for paging the result
            $row = $this->Potential->find('count');
            $count = $row;

            // calculate the total pages for the query
            if( $count > 0 )
            {
                $total_pages = ceil($count / $limit);
            }
            else
            {
                $total_pages = 0;
            }

            // if for some reasons the requested page is greater than the total
            // set the requested page to total page
            if( $page > $total_pages ) $page = $total_pages;

            // calculate the starting position of the rows
            $start = $limit * $page - $limit;

            // if for some reasons start position is negative set it to 0
            // typical case is that the user type 0 for the requested page
            if( $start < 0 ) $start = 0;

            // the actual query for the grid data
            $limit_range = $start . "," . $limit;
            $sort_range = $sidx . " " . $sord;

            $searchconditions = array();

            array_push(&$searchconditions, array('Potential.type =' => Inflector::singularize($this->passedArgs['by'])));

            if( isset($this->passedArgs['show']) && !empty($this->passedArgs['show']) )
            {
                if( $this->passedArgs['show'] == 'assigned' )
                {
                    array_push(&$searchconditions, array('Potential.assignedtoemployee_id' => $this->Session->read('Auth.Employee.id')));
                }
                else
                {
                    array_push(&$searchconditions, array('Potential.assignedtoemployee_id <>' => null));
                }
            }

            if( $this->params['url']['_search'] == 'true' )
            {
                if( isset($this->params['url']['firstname']) && !empty($this->params['url']['firstname']) )
                {
                    array_push(&$searchconditions, array('User.firstname LIKE' => $this->params['url']['firstname'] . '%'));
                }
                if( isset($this->params['url']['product']) && !empty($this->params['url']['product']) )
                {
                    array_push(&$searchconditions, array('Product.name LIKE' => $this->params['url']['product'] . '%'));
                }
                if( isset($this->params['url']['email1']) && !empty($this->params['url']['email1']) )
                {
                    array_push(&$searchconditions, array('User.email1 LIKE' => $this->params['url']['email1'] . '%'));
                }
                if( isset($this->params['url']['mobilephone']) && !empty($this->params['url']['mobilephone']) )
                {
                    array_push(&$searchconditions, array('User.mobilephone LIKE' => $this->params['url']['mobilephone'] . '%'));
                }
                if( isset($this->params['url']['location']) && !empty($this->params['url']['location']) )
                {
                    array_push(&$searchconditions, array('Location.name LIKE' => $this->params['url']['location'] . '%'));
                }

                $result = $this->Potential->find('all', array(
                    'conditions' => $searchconditions,
                    'link' => array(
                        'User' => array(
                            'fields' => array('id', 'firstname', 'lastname', 'mobilephone', 'email1')
                        ),
                        'Location' => array(
                            'fields' => array('id', 'name')
                        ),
                        'Product' => array(
                            'fields' => array('id', 'name')
                        )
                    ),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }
            else
            {
                $result = $this->Potential->find('all', array(
                    'conditions' => $searchconditions,
                    'link' => array(
                        'User' => array(
                            'fields' => array('id', 'firstname', 'lastname', 'mobilephone', 'email1')
                        ),
                        'Location' => array(
                            'fields' => array('id', 'name')
                        ),
                        'Product' => array(
                            'fields' => array('id', 'name')
                        )
                    ),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }

            $i = 0;
            $response->page = $page;
            $response->total = $total_pages;
            $response->records = $count;

            foreach($result as $result)
            {
                $response->rows[$i]['id'] = $result['Potential']['id'];

                $name = "<a href='" . APP_URL . "potentials/view/" . $result['Potential']['id'] . "'>" . $result['User']['firstname'] . " " . $result['User']['lastname'] . "</a>";
                $phone = $result['User']['mobilephone'];
                $email = $result['User']['email1'];
                $product = $result['Product']['name'];
                $location = $result['Location']['name'];
                $addactivity = "<a class='linkbutton' title='new activity' href='" . APP_URL . "potentialactivities/add/forpotential:" . $result['Potential']['id'] . "'><img src=" . APP_URL . "img/new_activity.gif /></a>";
                $sendemail = "<a class='linkbutton' title='send email' href='" . APP_URL . "potentialactivities/email/" . $result['Potential']['id'] . "'><img src=" . APP_URL . "img/email.png /></a>";
                $view = "<a class='linkbutton' title='view' href='" . APP_URL . "potentials/view/" . $result['Potential']['id'] . "'><img src=" . APP_URL . "img/view.png /></a>";
                $edit = "<a class='linkbutton' title='edit' href='" . APP_URL . "potentials/edit/" . $result['Potential']['id'] . "'><img src=" . APP_URL . "img/edit.png /></a>";
                $delete = "<a class='linkbutton' title='delete' href=\"#\" onclick=\"if(confirm('Are you sure you want to delete this ?')){window.location.href= '" . APP_URL . "potentials/delete/" . $result['Potential']['id'] . "'}\"><img src=" . APP_URL . "img/delete.png /></a>";
                if( $this->Session->read('Auth.Employee.employeetype_id') == Configure::read('employeetype.admin.id') )
                {
                    $actions = $addactivity . $sendemail . $view . $edit . $delete;
                }
                else
                {
                    $actions = $addactivity . $sendemail . $view . $edit;
                }

                $response->rows[$i]['cell'] = array($name, $product, $email, $phone, $location, $actions);
                $i++;
            }

            echo json_encode($response);
            //exit;
        }
    }

    function view($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid potential', true));
            $this->redirect(array('action' => 'index'));
        }
        //$this->set('potential', $this->Potential->read(null, $id));
        $potential = $this->Potential->find('first', array(
            'fields' => array('id', 'type', 'employee_id', 'assignedtoemployee_id', 'dateenquired', 'description'),
            'conditions' => array(
                'Potential.id' => $id
            ),
            'contain' => array(
                'User' => array(
                    'fields' => array('id', 'firstname', 'lastname', 'mobilephone', 'email1')
                ),
                'Product' => array(
                    'fields' => array('id', 'name')
                )
                ,
                'Location' => array(
                    'fields' => array('id', 'name')
                ),
                'Leadstage' => array(
                    'fields' => array('id', 'name')
                ),
                'Dealstage' => array(
                    'fields' => array('id', 'name')
                ),
                'Employee' => array(
                    'fields' => array('id', 'firstname')
                ),
                'Assignedtoemployee' => array(
                    'fields' => array('id', 'firstname')
                ),
                'Potentialactivity' => array(
                    'fields' => array('id', 'subject', 'duedate', 'nextfollowupdate', 'donedate', 'finalstatus'),
                    'Activitytype' => array(
                        'fields' => array('id', 'name')
                    ),
                    'Employee' => array(
                        'fields' => array('id', 'firstname')
                    ),
                    'Assignedtoemployee' => array(
                        'fields' => array('id', 'firstname')
                    )
                ),
                'Task' => array(
                    'fields' => array('id', 'name'),
                    'Tasktemplate' => array(
                        'fields' => array('id', 'name')
                    ),
                    'Employee' => array(
                        'fields' => array('id', 'firstname')
                    ),
                    'Assignedtoemployee' => array(
                        'fields' => array('id', 'firstname')
                    )
                )
            )
        ));
        $this->set(compact('potential'));
    }

    function add()
    {
        $this->_addPotential();
    }

    function edit($id = null)
    {
        $this->_editPotential($id);
    }

    function delete($id = null)
    {
        $this->_deletePotential($id);
    }

    /**
     * Shows the assigned potentials of current logged in user only
     */
    function assigned()
    {
        $this->Potential->recursive = 0;
        $this->paginate['Potential'] = array(
            'conditions' => array(
                'Potential.assignedtoemployee_id' => $this->Session->read('Auth.Employee.id')
            )
        );
        $potentials = $this->paginate('Potential');
        $this->set('potentials', $potentials);
    }

    function admin_index()
    {
        //if( isset($this->params['named']['ajax']) && $this->params['named']['ajax'] == '1' )
        if( $this->RequestHandler->isAjax() )
        {
            //pr($this->params);
            $this->autoRender = false;

            // get how many rows we want to have into the grid - rowNum parameter in the grid
            $limit = $this->params['url']['rows'];

            // get index row - i.e. user click to sort. At first time sortname parameter -
            // after that the index from colModel
            $sidx = $this->params['url']['sidx'];

            // sorting order - at first time sortorder
            $sord = $this->params['url']['sord'];

            $page = $this->params['url']['page'];

            // if we not pass at first time index use the first column for the index or what you want
            if( !$sidx ) $sidx = 1;

            // calculate the number of rows for the query. We need this for paging the result
            $row = $this->Potential->find('count');
            $count = $row;

            // calculate the total pages for the query
            if( $count > 0 )
            {
                $total_pages = ceil($count / $limit);
            }
            else
            {
                $total_pages = 0;
            }

            // if for some reasons the requested page is greater than the total
            // set the requested page to total page
            if( $page > $total_pages ) $page = $total_pages;

            // calculate the starting position of the rows
            $start = $limit * $page - $limit;

            // if for some reasons start position is negative set it to 0
            // typical case is that the user type 0 for the requested page
            if( $start < 0 ) $start = 0;

            // the actual query for the grid data
            $limit_range = $start . "," . $limit;
            $sort_range = $sidx . " " . $sord;

            $this->Potential->recursive = -1;

            if( $this->params['url']['_search'] == 'true' )
            {
                $result = $this->Potential->find('all', array(
                    'conditions' => array(
                        'User.firstname LIKE' => '%' . $this->params['url']['name'] . '%',
                    ),
                    'contain' => array(
                        'User' => array(
                            'fields' => array('name')
                        )
                    ),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }
            else
            {
                $result = $this->Potential->find('all', array(
                    'contain' => array(
                        'User' => array(
                            'fields' => array('name')
                        )
                    ),
                    'order' => $sort_range,
                    'limit' => $limit_range
                ));
            }

            $i = 0;
            $response->page = $page;
            $response->total = $total_pages;
            $response->records = $count;

            foreach($result as $result)
            {
                $response->rows[$i]['id'] = $result['Potential']['id'];

                $name = "<a href='" . APP_URL . "admin/potentials/view/" . $result['Potential']['id'] . "'>" . $result['User']['name'] . "</a>";
                $type = "<a href='" . APP_URL . "admin/potentials/view/" . $result['Potential']['id'] . "'>" . $result['Potential']['type'] . "</a>";
                $view = "<a title='view' href='" . APP_URL . "admin/potentials/view/" . $result['Potential']['id'] . "'>view</a>";
                $edit = "<a title='edit' href='" . APP_URL . "admin/potentials/edit/" . $result['Potential']['id'] . "'>edit</a>";
                $delete = "<a title='delete' href=\"#\" onclick=\"if(confirm('Are you sure you want to delete this ?')){window.location.href= '" . APP_URL . "admin/potentials/delete/" . $result['Potential']['id'] . "'}\">delete</a>";
                $actions = $view . "    " . $edit . "    " . $delete;

                $response->rows[$i]['cell'] = array($name, $type, $actions);
                $i++;
            }

            echo json_encode($response);
            //exit;
        }
    }

    function admin_view($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid potential', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('potential', $this->Potential->read(null, $id));
    }

    function admin_add()
    {
        $this->_addPotential();
    }

    function admin_edit($id = null)
    {
        $this->_editPotential($id);
    }

    function admin_delete($id = null)
    {
        $this->_deletePotential($id);
    }

    /*
     * check if the user is already a potential for the same product
     */

    function alreadyapotential($userid = null, $productid = null)
    {
        $this->autoRender = false;
        $userid = empty($userid) ? $this->params['url']['userid'] : $userid;
        $productid = empty($productid) ? $this->params['url']['productid'] : $productid;
        $potentialexists = $this->Potential->find('all', array(
            'conditions' => array(
                'Potential.user_id' => $userid,
                'Potential.product_id' => $productid
            ),
            'link' => array(
                'User' => array(
                    'fields' => array('id', 'firstname', 'lastname')
                ),
                'Product' => array(
                    'fields' => array('id', 'name')
                )
            )
        ));
        if( $this->RequestHandler->isAjax() )
        {
            if( $potentialexists )
            {
                return json_encode($potentialexists);
            }
            else return false;
        }
        else
        {
            if( $potentialexists ) return $potentialexists;
            else return false;
        }
    }

    function _addPotential()
    {
        if( !empty($this->data) )
        {
            $check = $this->alreadyapotential($this->data['Potential']['user_id'], $this->data['Potential']['product_id']);
            if( $check )
            {
                $this->Session->setFlash(__('The user "' . $check[0]['User']['firstname'] . " " . $check[0]['User']['lastname'] . '" is already a potential for product "' . $check[0]['Product']['name'] . '"', true), 'notice');
                $this->redirect(array('controller' => 'users', 'action' => 'index'));
            }

            $this->Potential->create();
            if( $this->Potential->save($this->data) )
            {
                $this->Session->setFlash(__('The potential has been saved', true), 'success');
                $this->redirect(array('controller' => 'users', 'action' => 'index'));
            }
            else
            {
                $this->Session->setFlash(__('The potential could not be saved. Please, try again.', true), 'notice');
            }
        }

        /* if the employee is coming from 'convert to potential' link then the $users will have only one entry in it */
        if( !empty($this->passedArgs[0]) )
        {
            $users = $this->Potential->User->find('list', array(
                'conditions' => array(
                    'User.id' => $this->passedArgs[0]
                )
            ));
        }
        else
        {
            $users = $this->Potential->User->find('list');
        }

        $products = $this->Potential->Product->find('list');
        $leadstages = $this->Potential->Leadstage->find('list');
        $dealstages = $this->Potential->Dealstage->find('list');

        $assignedtoemployees = $this->Potential->Employee->find('list', array(
            'conditions' => array('employeetype_id <>' => Configure::read('employeetype.admin.id'))
        ));

        $locations = $this->Potential->Location->find('list');

        $this->set(compact('users', 'products', 'leadstages', 'dealstages', 'assignedtoemployees', 'locations'));
    }

    function _editPotential($id = null)
    {
        if( !$id && empty($this->data) )
        {
            $this->Session->setFlash(__('Invalid potential', true), 'error');
            $this->redirect(array('action' => 'index'));
        }
        if( !empty($this->data) )
        {
            if( $this->Potential->save($this->data) )
            {
                $this->Session->setFlash(__('The potential has been edited successfully', true), 'success');
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash(__('The potential could not be saved. Please, try again.', true));
            }
        }
        if( empty($this->data) )
        {
            $this->data = $this->Potential->read(null, $id);
        }

        $users = $this->Potential->User->find('list');
        $products = $this->Potential->Product->find('list');
        $leadstages = $this->Potential->Leadstage->find('list');
        $dealstages = $this->Potential->Dealstage->find('list');

        $assignedtoemployees = $this->Potential->Employee->find('list', array(
            'conditions' => array('employeetype_id <>' => Configure::read('employeetype.admin.id'))
        )); //employee who is assigned the overall responsibility of this potential

        $locations = $this->Potential->Location->find('list');

        $this->set(compact('users', 'products', 'leadstages', 'dealstages', 'assignedtoemployees', 'locations'));
    }

    function _deletePotential($id = null)
    {
        if( !$id )
        {
            $this->Session->setFlash(__('Invalid id for potential', true));
            $this->redirect(array('action' => 'index'));
        }
        if( $this->Potential->delete($id) )
        {
            $this->Session->setFlash(__('Potential deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Potential was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

}

?>